package com.face.server.service.impl;

import com.face.RespMsg;
import com.face.server.dao.JoinedDAO;
import com.face.server.dao.VisitorDAO;
import com.face.server.entity.Joined;
import com.face.server.entity.Student;
import com.face.server.entity.Visitor;
import com.face.server.repository.JoinedRepository;
import com.face.server.repository.VisitorRepository;
import com.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

@Service
public class VisitorService {

    @Autowired
    JoinedRepository joinedRepository;

    @Autowired
    JoinedDAO joinedDAO;

    @Autowired
    FaceDetectImpl faceDetectService;

    @Autowired
    VisitorDAO visitorDAO;

    public RespMsg save(Visitor visitor, String id) {
        Date now = new Date();
        long vistorNum = visitorDAO.countByStudentId(id, now);
        if (vistorNum > 5) {
            return RespMsg.error("对不起，您的有效访问者超过5人，请去申请");
        }
        Student student = joinedDAO.findOne(id);
        visitor.setStudent(student);
        visitor.setType(1);
        visitor.setDormitoryBuildNum(student.getDormitoryBuildNum());
        visitor.setDormitoryBuild(student.getDormitoryBuild());
        visitor.setDormitoryNum(student.getDormitoryNum());
        joinedRepository.save(visitor);
        return RespMsg.build(visitor.getId());
    }

    public RespMsg findByStudentId(String id) {
        Date date = new Date();
        return RespMsg.build(
                visitorDAO.findByStudentId(id, date)
        );
    }

    public RespMsg findById(String id) {
        Visitor visitor = visitorDAO.findOne(id);
        return visitor == null ? RespMsg.error("对不起，当前访问者不存在") : RespMsg.build(visitor);
    }


    public RespMsg saveFaceModels(MultipartFile file, String id) throws IOException {
        Visitor visitor = visitorDAO.findOne(id);
        return faceDetectService.saveFaceModels(file, visitor);
    }
}
